package com.squeekeek.util.qrcode.Ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;

public class ImageCaptureCallback implements PictureCallback {
	// Note: Activity is a subclass of Context
	private Activity myActivity;
	
	public ImageCaptureCallback(Activity a) {
		this.myActivity = a;
	}
	
	@Override
	public void onPictureTaken(byte[] data, Camera c) {
		FileOutputStream fos;
		File fileInstance;
		ProgressDialog loadDialog;
		QRDecodeTask threadTask;
		
		try {
			// Save image to file
			fileInstance = getOutputImageFile(this.myActivity);
			
			if(fileInstance == null) {
				Log.d("QRCode", "PictureHandle: :/");
				return;
			}
			
			fos = new FileOutputStream(fileInstance);
			fos.write(data);
			fos.close();
			
			// Dispatch a progress bar :D
			loadDialog = new ProgressDialog(this.myActivity);
			loadDialog.setCancelable(true);
			loadDialog.setMessage("Decoding QR Code...");
			loadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			loadDialog.setIndeterminate(true);
			loadDialog.show();
			
			// Execute the QR decoding part in another task
			threadTask = new QRDecodeTask(this.myActivity, fileInstance, loadDialog);
			threadTask.execute();
		}
		catch(FileNotFoundException e) {
			Log.d("QRCode", e.getMessage());
		}
		catch(IOException e) {
			Log.d("QRCode", e.getMessage());
		}
	}
	
	private File getOutputImageFile(Context ctx) {
		String timeStamp;
		File appMediaDir;
		File mediaFile;
		
		appMediaDir = new File(ctx.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "qrcode");
		
		if(!appMediaDir.exists()) {
			if(!appMediaDir.mkdirs()) {
				//Log.d("Output", "Cannot create dir in media store.");
				return null;
			}
		}
		
		timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
		mediaFile = new File(appMediaDir.getPath() + File.separator + "qr_" + timeStamp + ".jpg");

		return mediaFile;
	}
}
